package com.itheima.controller;

import com.itheima.anno.LogOperation;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {
    //private static final Logger log = LoggerFactory.getLogger(DeptController.class);
    @Autowired
    private DeptService deptService;

    //@RequestMapping(value = "/depts",method = RequestMethod.GET)
    @LogOperation
    @GetMapping
    public Result list(){
//        System.out.println("查询全部的部门数据");
        log.info("查询全部的部门数据");
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }


    //方式一
//    @DeleteMapping("/depts")
//    public Result delete(HttpServletRequest request){
//        String idString = request.getParameter("id");
//        int id = Integer.parseInt(idString);
//        System.out.println("根据id删除部门数据"+id);
//        return Result.success();
//    }
    //方式二 使用RequestParam注解 required代表是否是必须的
//    @DeleteMapping("/depts")
//    public Result delete(@RequestParam(value = "id",required = false) Integer deptId){
//        System.out.println("根据id删除部门数据"+deptId);
//        return Result.success();
//    }

    //方式三 前端传递的请求参数名 与服务端方法形参名称一致 就可以省略RequestParam注解
    @LogOperation
    @DeleteMapping
    public Result delete(Integer id){
//        System.out.println("根据id删除部门数据"+id);
        log.info("根据id删除部门数据"+id);
        deptService.deleteById(id);
        return Result.success();
    }

    @LogOperation
    @PostMapping
    public Result add(@RequestBody Dept dept){
//        System.out.println(dept);
        log.info("新增部门：{}",dept);
        deptService.add(dept);
        return Result.success();
    }

    //用@PathVariable注解标识路径参数
//    @GetMapping("/depts/{id}")
//    public Result getInfo(@PathVariable("id") Integer deptId){
//        System.out.println("根据Id查询部门："+deptId);
//        return Result.success();
//    }

    //路径参数名和方法形参名相同 可以省略@PathVariable注解中的value值部分
    @LogOperation
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable Integer id){
//        System.out.println("根据Id查询部门："+id);
        log.info("根据Id查询部门：{}",id);
        Dept dept  = deptService.getById(id);
        return Result.success(dept);
    }

    @LogOperation
    @PutMapping
    public Result update(@RequestBody Dept dept){
//        System.out.println("修改部门："+dept);
        log.info("修改部门：{}",dept);
        deptService.update(dept);
        return Result.success();
    }


}
